﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using IPTools.Core;
using Microsoft.AspNetCore.Http;
using RxxAdmin.Common.Extensions;
using RxxAdmin.IServices;
using RxxAdmin.Model.Logs;
using UAParser;

namespace RxxAdmin.Services;

public class OperationLogService : BaseServices<OperationLog>, IOperationLogService
{
    private readonly IHttpContextAccessor _httpContextAccessor;

    public OperationLogService(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }
    public async Task<List<long>> Add(string title, OperEnum opertype, string requestmethod, string name, string method, string requestparam, string requestresult)
    {
        OperationLog operationLog = GetInfoByHttpContext(_httpContextAccessor.HttpContext);
        operationLog.Title = title; // 操作模块 
        operationLog.OperType = opertype; // 操作类型 
        operationLog.RequestMethod = requestmethod; // 请求方法
        operationLog.OperUser = name; 
        operationLog.Method = method; // 操作方法 
        operationLog.RequestParam = requestparam; // 请求参数 
        operationLog.RequestResult = requestresult; // 请求结果 
        operationLog.DateTime = DateTime.Now;
        return await AddSplit(operationLog);
    }
    public OperationLog GetInfoByHttpContext(HttpContext context)
    {       
        var ipAddr = context.GetClientIp();
        IpInfo location;
        if (ipAddr == "127.0.0.1")
        {
            location = new IpInfo() { Province = "本地", City = "本机" };
        }
        else
        {
            try
            {
                location = IpTool.Search(ipAddr);
            }
            catch
            {
                location = new IpInfo() { Province = ipAddr, City = "未知地区" };
            }
        }
        OperationLog entity = new()
        {
            OperIp = ipAddr,
            OperLocation = location.Province + "-" + location.City
        };
        return entity;
    }
}
